<template>
  <a-drawer
    title="新建菜单"
    :width="500"
    :visible="visible"
    :body-style="{ paddingBottom: '80px' }"
    :closable="false"
    @close="onClose"
  >
    <a-form :form="form" class="form">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item style="display:none">
            <a-input v-decorator="['id']"/>
          </a-form-item>
          <a-form-item label="上级菜单">
            <a-tree-select
              v-decorator="['parentId', {rules: [{ required: true, message: '请选择上级权限' }]}]"
              :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
              :treeData="menuData"
              placeholder="上级权限"
            ></a-tree-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="菜单类型">
            <a-radio-group
              :disabled="submitFlag === 'edit'"
              @change="menuTypeChange"
              v-decorator="['menuType', {initialValue: 'M', rules: [{required: true}]}]">
              <a-radio value="M">
                目录
              </a-radio>
              <a-radio value="C">
                菜单
              </a-radio>
              <a-radio value="F">
                按钮
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="菜单名称">
            <a-input
              @blur="checkName"
              :class="checkMenuNameResult ? 'border_color' : ''"
              v-decorator="['name',{rules: [{ required: true, message: '请输入菜单名称', pattern: /^[^\s]*$/ }],},]"
              placeholder="请输入菜单名称"
            >
            </a-input>
            <span class="check" v-if="checkMenuNameResult && this.form.getFieldValue('name')!==''">
              菜单名称已存在
            </span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="排序号">
            <a-input-number
              :min="0"
              :max="100"
              v-decorator="['orderNum',{rules: [{ required: true, message: '请输入排序号'}],},]"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12" v-if="menuType!=='F'" >
          <a-form-item label="菜单图标">
            <a-input
              v-decorator="['icon',{rules: [{ required: false, message: '请选择图标' }]}]"
              ref="iconInput"
              @click="iconSelect()"
              enterButton="选择图标"
              placeholder="选择图标"
            >
              <a-icon slot="prefix" :type="icon" />
              <a-icon slot="suffix" type="close-circle" @click="emitEmpty" />
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="menuType!=='F'">
          <a-form-item>
            <span slot="label">
              是否外链
              <a-tooltip placement="topLeft" title="选择是外链则路由地址需要以`http(s)://`开头">
                <a-icon type="question-circle" theme="twoTone"/>
              </a-tooltip>
            </span>
            <a-radio-group
              v-decorator="['outsideTheChain', {initialValue: 'false'}]">
              <a-radio value="true">
                是
              </a-radio>
              <a-radio value="false">
                否
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12" v-if="menuType!=='F'">
          <a-form-item label="隐藏菜单">
            <a-radio-group
              v-decorator="['hidden', {initialValue: '0'}]">
              <a-radio value="1">
                是
              </a-radio>
              <a-radio value="0">
                否
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="menuType!=='F'">
          <a-form-item>
            <span slot="label">
              隐藏子菜单
              <a-tooltip placement="topLeft" title="隐藏目录或是菜单下面的子菜单">
                <a-icon type="question-circle" theme="twoTone"/>
              </a-tooltip>
            </span>
            <a-radio-group
              v-decorator="['hideChildren', {initialValue: '0'}]">
              <a-radio value="1">
                是
              </a-radio>
              <a-radio value="0">
                否
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12" v-if="menuType!=='F'">
          <a-form-item>
            <span slot="label">
              路由地址
              <a-tooltip placement="topLeft" title="组件名称或views文件下的路径 如: system/User(注意不需要加前'/')">
                <a-icon type="question-circle" theme="twoTone"/>
              </a-tooltip>
            </span>
            <a-input
              v-decorator="['component', {rules: [{ required: true, message: '请输入路由地址' }]}]"
              placeholder="请输入路由地址"
            >
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="menuType!=='F'">
          <a-form-item>
            <span slot="label">
              需要管理员权限
              <a-tooltip placement="topLeft" title="是否是需要管理员权限">
                <a-icon type="question-circle" theme="twoTone"/>
              </a-tooltip>
            </span>
            <a-radio-group
              v-decorator="['isSuperAdminRead', {initialValue: 'false'}]">
              <a-radio value="true">
                是
              </a-radio>
              <a-radio value="false">
                否
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12" v-if="menuType!=='M'">
          <a-form-item label="权限字符">
            <a-input
              v-decorator="['perms',{rules: [{ required: true, message: '请输入权限字符', pattern: /^[^\s]*$/ }],},]"
              placeholder="请输入权限字符"
            >
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item>
            <span slot="label">
              状态
              <a-tooltip placement="topLeft" title="启用/禁用">
                <a-icon type="question-circle" theme="twoTone"/>
              </a-tooltip>
            </span>
            <a-radio-group
              v-decorator="['status', {initialValue: '1'}]">
              <a-radio value="1">
                启用
              </a-radio>
              <a-radio value="0">
                禁用
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="menuType!=='F'">
          <a-form-item>
            <span slot="label">
              重定向地址
              <a-tooltip placement="topLeft" title="重定向地址用于,目录或菜单默认跳转地址">
                <a-icon type="question-circle" theme="twoTone"/>
              </a-tooltip>
            </span>
            <a-input
              v-decorator="['redirect']"
              placeholder="请输入重定向地址"
            >
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="menuType!=='F'">
          <a-form-item>
            <span slot="label">
              路由唯一键
              <a-tooltip placement="topLeft" title="路由唯一键：如'user,system'用于确定目录或者菜单的唯一标示">
                <a-icon type="question-circle" theme="twoTone"/>
              </a-tooltip>
            </span>
            <a-input
              @blur="checkKey"
              :class="checkMenuKeyResult ? 'border_color' : ''"
              v-decorator="['key',{rules: [{ required: true, message: '请输入动态菜单唯一键' }]}]"
              placeholder="请输入路由唯一键"
            >
            </a-input>
            <span class="check" v-if="checkMenuKeyResult && this.form.getFieldValue('key')!==''">
              菜单路由唯一键已存在
            </span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item>
            <span slot="label">
              国际化标题
              <a-tooltip placement="topLeft" title="国际化标题: 如系统管理(menu.system) 英文格式用.隔开">
                <a-icon type="question-circle" theme="twoTone"/>
              </a-tooltip>
            </span>
            <a-input
              v-decorator="['title',{rules: [{ required: true, message: '请输入国际化标题' }]}]"
              placeholder="请输入国际化标题"
            >
            </a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item>
            <span slot="label">
              归属类型
              <a-tooltip placement="topLeft" title="归属类型: 公共的(都可见),选择了对应的租户后,该目录,菜单,方法就只在改租户用户下可见,">
                <a-icon type="question-circle" theme="twoTone"/>
              </a-tooltip>
            </span>
            <a-select
              :class="affiliationFlag ? 'border_color' : ''"
              mode="multiple"
              placeholder="请选择归属类型"
              v-decorator="['tenantCodes',{rules: [{ required: true, message: '请选择归属类型'}]}]"
              @change="handleChange"
            >
              <a-select-option v-for="(action) in tenantInfo" :key="action.tenantCode">
                {{ action.tenantName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="描述">
            <a-textarea
              v-decorator="['remark']"
              :rows="4"
              placeholder="在这里输入描述内容..."></a-textarea>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-popconfirm title="真的放弃编辑吗?" @confirm="onClose">
        <a-icon slot="icon" type="question-circle-o" style="color: red" />
        <a-button :style="{ marginRight: '8px' }">
          取消
        </a-button>
      </a-popconfirm>
      <a-button type="primary" @click="menuSubmit">
        保存
      </a-button>
    </div>
    <iconSelector-modal ref="modal" @ok="setIcon" :icon="icon" />
  </a-drawer>
</template>

<script>
import pick from 'lodash.pick'
import { tenantInfo, findMenuAndPermissionList, checkMenuName, checkMenuKey, addMenu, findMenuDetails, editMenu } from '@/api/system'
import IconSelectorModal from './IconSelectorModal.vue'
import message from 'ant-design-vue/es/message'
export default {
  name: 'MenuModal',
  components: {
    IconSelectorModal
  },
  data () {
    return {
      menuData: [{ key: 0, value: '0', title: '无', menuType: '无' }],
      visible: false,
      form: this.$form.createForm(this),
      treeData: [],
      mdl: {},
      submitFlag: null,
      icon: 'smile',
      menuType: 'M',
      checkMenuNameResult: false,
      checkMenuKeyResult: false,
      affiliationFlag: false,
      menuList: [],
      menuNewList: [],
      tenantInfo: [{ tenantCode: 'common', tenantName: '所有' }]
    }
  },
  created () {
    this.loadTenantInfo()
  },
  methods: {
    handleChange (value) {
      if (value.length > 1 && value.indexOf('common') !== -1) {
        message.error('归属不能同时选择所有与租户')
        this.affiliationFlag = true
      } else {
        this.affiliationFlag = false
      }
    },
    loadTenantInfo () {
      tenantInfo().then(res => {
        this.tenantInfo = this.tenantInfo.concat(res.data)
      })
    },
    menuTypeChange (e) {
      this.icon = 'smile'
      // this.form.resetFields()
      this.menuType = e.target.value
      let defaultData = [{ key: 0, value: '0', title: '无', menuType: '无' }]
      findMenuAndPermissionList().then(res => {
        // 根据不同的menuType设置禁用标示
        if (this.menuType === 'M') {
          res.data.filter(menu => menu.menuType !== 'M')
            .forEach(menu1 => {
              menu1.disabled = true
            })
        } else {
          res.data.filter(menu => menu.menuType !== 'C')
            .forEach(menu1 => {
              menu1.disabled = true
            })
          defaultData = []
        }
        this.buildTree(res.data, defaultData, '0')
        this.menuData = defaultData
      })
    },
    emitEmpty () {
      this.$refs.iconInput.focus()
      this.icon = 'smile'
      this.form.setFieldsValue({ icon: '' })
    },
    setIcon (icon) {
      this.icon = icon
      this.form.setFieldsValue({ icon: icon })
    },
    iconSelect () {
      this.$refs.modal.show()
    },
    onClose () {
      this.visible = false
      this.menuType = 'M'
      this.checkMenuKeyResult = false
    },
    add () {
      this.submitFlag = 'save'
      this.form.resetFields()
      this.mdl = {}
      this.visible = true
      this.loadMenu()
    },
    edit (record) {
      this.visible = true
      findMenuDetails({ menuId: record.id }).then(res => {
        this.submitFlag = 'edit'
        this.mdl = Object.assign({}, res.data)
        this.mdl.outsideTheChain = (res.data.target !== null).toString()
        this.mdl.hidden = res.data.hidden.toString()
        this.mdl.hideChildren = res.data.hideChildren.toString()
        this.mdl.isSuperAdminRead = res.data.isSuperAdminRead.toString()
        this.icon = res.data.icon
        this.visible = true
        if (res.data.menuType === 'M') {
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.mdl, 'id', 'parentId', 'menuType', 'name', 'orderNum', 'icon', 'hidden', 'hiddenChildren', 'component',
              'isSuperAdminRead', 'status', 'redirect', 'key', 'title', 'outsideTheChain'))
          })
        } else if (res.data.menuType === 'C') {
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.mdl, 'id', 'parentId', 'menuType', 'name', 'orderNum', 'icon', 'hidden', 'hiddenChildren', 'component',
              'isSuperAdminRead', 'perms', 'status', 'redirect', 'key', 'title', 'outsideTheChain'))
          })
        } else {
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.mdl, 'id', 'parentId', 'menuType', 'name', 'orderNum', 'perms', 'status', 'title'))
          })
        }
      }).catch(res => {
        this.$message.error(((res.response || {}).data || {}).message || res.message)
      })
      this.loadMenu()
    },
    menuSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err && !this.checkMenuNameResult && !this.checkMenuKeyResult && !this.affiliationFlag) {
          if (this.submitFlag === 'save') {
            addMenu(values).then(res => {
              if (res.code === 0) {
                this.$message.success('保存菜单成功')
                this.$emit('ok')
                this.visible = false
              }
            }).catch(res => {
              this.$message.error(((res.response || {}).data || {}).message || res.message)
            })
          } else {
            editMenu(values).then(res => {
              this.$message.success('编辑菜单成功')
              this.$emit('ok')
              this.visible = false
            }).catch(res => {
              this.$message.error(((res.response || {}).data || {}).message || res.message)
            })
          }
        }
      })
    },
    loadMenu () {
      findMenuAndPermissionList().then(res => {
        // 根据不同的menuType设置禁用标示
        if (this.menuType === 'M') {
          res.data.filter(menu => menu.menuType !== 'M')
            .forEach(menu1 => {
            menu1.disabled = true
          })
        } else {
          res.data.filter(menu => menu.menuType !== 'C')
            .forEach(menu1 => {
              menu1.disabled = true
            })
        }
        this.buildTree(res.data, this.menuData, '0')
      })
      this.menuData = [{ key: 0, value: '0', title: '无', menuType: '无' }]
    },
    buildTree (list, arr, parentId) {
      list.forEach(item => {
        if (item.parentId === parentId) {
          const child = {
            key: item.id,
            value: item.id + '',
            title: item.name,
            menuType: item.menuType,
            disabled: item.disabled,
            children: []
          }
          this.buildTree(list, child.children, item.id)
          arr.push(child)
        }
      })
    },
    async checkName () {
      const parameter = {
        menuName: this.form.getFieldValue('name'),
        menuId: this.form.getFieldValue('id')
      }
      if (parameter.menuName !== '') {
        await checkMenuName(parameter).then(res => {
          this.checkMenuNameResult = res.data
        })
      }
    },
    async checkKey () {
      if (this.form.getFieldValue('key') !== '') {
        const parameter = {
          menuKey: this.form.getFieldValue('key'),
          menuId: this.form.getFieldValue('id')
        }
        await checkMenuKey(parameter).then(res => {
          this.checkMenuKeyResult = res.data
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .check {
    position: absolute;
    top: 16px;
    left: 0;
    color: red
  }
  .border_color {
    border: 1px solid red;
  }
</style>
